{% extends "base.html" %}

{% block content %}
<div class="page-title">
    <h3 id="data-count-message">加载中...</h3>
</div>
<div class="form-container">
    <form id="export-product-form">
        <div class="button-container">
            <button type="submit" class="login-button">导出CSV</button>
        </div>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        fetch('/api/products/count')
            .then(response => response.json())
            .then(data => {
                document.getElementById('data-count-message').textContent = `当前存有 ${data.count} 条数据，点击下面的按钮导出`;
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('data-count-message').textContent = '无法加载数据数量';
            });
    });

    document.getElementById('export-product-form').addEventListener('submit', function(event) {
        event.preventDefault();

        fetch('/api/products/export/csv')
            .then(response => {
                if (response.ok) {
                    return response.blob();
                } else {
                    throw new Error('导出失败');
                }
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = 'products.csv';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('导出失败');
            });
    });
</script>
{% endblock %}
